package com.syf.core;

import com.syf.core.cont.SyfCoreCont;
import com.syf.core.engine.SyFrameContext;
import com.syf.core.server.SyServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ConfigurableApplicationContext;

import java.util.Map;

@Slf4j
public class SyApplicationShutdownHook {

    private final ConfigurableApplicationContext springContext;

    SyApplicationShutdownHook(ConfigurableApplicationContext springContext) {
        this.springContext = springContext;
    }

    public void shutdownGracefully() {

        log.info("=============正在停止所有SyServer===============");
        Map<String, SyServer> serverBeansMap = springContext.getBeansOfType(SyServer.class, true, false);
        if (serverBeansMap != null) {
            serverBeansMap.values().forEach(syServer -> {
                syServer.gracefullyShutdown();
                log.info("已停止SyServer: {}", syServer.getClass().getTypeName());
            });
        }
        log.info("=============已停止所有SyServer===============");

        try {
            Thread.sleep(30000L);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        log.info("=============正在关闭Spring IOC===============");
        // 将spring ioc容器关闭
        springContext.stop();
        log.info("=============应用系统已优雅停机===============");
    }
}
